<script setup>
import { onLaunch, onShow, onHide } from "@dcloudio/uni-app";
import { useUserStore } from "@/store/user";
import { initApp } from "@/utils/app";
import { useI18n } from "vue-i18n";
import { initLanguage } from "@/utils/language";

// 应用启动时初始化
onLaunch(() => {
  // 初始化语言设置
  const i18n = useI18n();
  initLanguage(i18n);

  // 初始化应用和用户状态
  const { isLoggedIn, userStore } = initApp();
  // 延迟执行路由检查，确保页面已初始化
  setTimeout(() => {
    checkAndRedirect(userStore);
  }, 1000);
});

// 路由检查和重定向逻辑
const checkAndRedirect = (userStore) => {
  try {
    // 获取当前页面路径
    const pages = getCurrentPages();
    let currentRoute = "";
    if (pages && pages?.length) {
      const currentPage = pages[pages.length - 1];
      currentRoute = currentPage ? currentPage.route : "";
    }

    // 白名单路径（修正格式）
    const whiteList = ["pages/index/index", "pages/payDetail/payDetail"];

    // 如果路由为空或不在白名单中，且未登录，则跳转到登录页
    if (
      (!currentRoute || !whiteList.includes(currentRoute)) &&
      !userStore.checkLoginStatus()
    ) {
      uni.reLaunch({
        url: "/pages/login/login",
      });
    }
  } catch (error) {
    // 出错时默认跳转到登录页
    if (!userStore.checkLoginStatus()) {
      uni.reLaunch({
        url: "/pages/login/login",
      });
    }
  }
};

onShow(() => {
  // 应用显示时检查登录状态
  const userStore = useUserStore();
  if (!userStore.checkLoginStatus()) {
    // 可以在这里添加额外的登录状态检查逻辑
  }
});

onHide(() => {});
</script>

<style lang="scss">
/*每个页面公共css */
@import "@/uni_modules/uview-plus/index.scss";
@import "@/common/styles/global.scss";
</style>
